/********************************************************************
    This program is based on the technique of tomato Francesco Cirillo
	http://www.pomodorotechnique.com timer is a software for this technique.

    Copyright (C) 2009  Massimo Di Giulio mailto:info@satimax.it mailto:digiulio.massimo@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.



********************************************************************/

#pragma once
#include "IBreak.h"
#include "DefaultBreak.h"
#include "ISerializer.h"
using namespace System::IO;
using namespace System;
using namespace System::Text;


public ref class Serializer : public ISerializer
{
private:
	String^ path; 
	FileStream^ fs;
	

public:
	Serializer(void);
	~Serializer(void);
	virtual bool open() override
	{
			if ( !File::Exists( this->path ))
			{
				//File::Delete( path );
				this->fs = File::Create( this->path );
				ISerializer::exist = false;
				IBreak^ b = gcnew DefaultBreak();
				this->storeValue(b);
				this->close();
			} 
			this->fs = File::Open( this->path, FileMode::Open ,FileAccess::ReadWrite,FileShare::ReadWrite);
			ISerializer::exist=true;
		
		return true;
	}
	virtual void close() override 
	{
		this->fs->Close();
	}
	virtual void loadValue(IBreak^ b) override
	{
		
		if(ISerializer::exist){
		array<Byte>^ab = gcnew array<Byte>(1024);
		UTF8Encoding^ temp = gcnew UTF8Encoding( true );
		while ( fs->Read( ab, 0, ab->Length ) > 0 ){}
		String^ re = temp->GetString( ab );
		String^ delimStr = ";";
		array<Char>^delimiter = delimStr->ToCharArray();
		array<String^>^ split = nullptr;
		split = re->Split( delimiter);
		b->setShortBreak(  (long)Convert::ToInt32( split[0]));
		b->setLongBreak( (long)Convert::ToInt32(split[1]));
		}

	}
	virtual void storeValue(IBreak^ b) override 
	{


		String^ st = String::Format("{0};{1};",b->getShortBreak(),b->getLongBreak());
		UTF8Encoding^ ut = gcnew UTF8Encoding( true );
		array<Byte>^info = ut->GetBytes( st );
		this->fs->Write( info, 0, info->Length );



	}
	
};
